<template>
  <a-modal
    :visible="visible"
    :afterClose="hanldeAfterClose"
    @cancel="close"
    @ok="handleSubmit"
    :width="1400"
    :confirmLoading="isSubmiting"
    :title="$isEmpty(data) ? '新建档案' : '修改档案'"
  >
    <a-spin :spinning="spinning">
      <a-tabs v-model="activeKey">
        <a-tab-pane key="1" tab="档案基本信息">
          <a-form :form="form" :labelCol="{ span: 8 }" :wrapperCol="{ span: 16 }">
            <a-row :gutter="[16, 16]" type="flex">
              <a-col :span="8">
                <a-form-item label="档案类型">
                  <a-input disabled value="公共租赁住房新增保障档案"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="建档日期（电）">
                  <!-- <div slot="extra">
                    <span class="text-warning">锁定时间：</span>
                    <a-switch v-model="lockTime"></a-switch>
                  </div> -->
                  <a-date-picker
                    placeholder="请选择建档日期"
                    value-format="YYYY-MM-DD"
                    v-decorator="['CreateDate', { rules: [{ required: true, message: '请选择建档日期' }] }]"
                  ></a-date-picker>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="档案名称">
                  <a-input
                    placeholder="请输入档案名称"
                    v-decorator="['Name', { rules: [{ required: true, message: '请输入档案名称' }] }]"
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="姓名">
                  <a-input
                    placeholder="请输入姓名"
                    v-decorator="['AKey', { rules: [{ required: true, message: '请输入姓名' }] }]"
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="身份证">
                  <a-input
                    placeholder="请输入身份证"
                    v-decorator="[
                      'AValue',
                      {
                        rules: [
                          { required: true, message: '', whitespace: true, trigger: 'change' },
                          { validator: validateIDCard },
                        ],
                      },
                    ]"
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="是否自动索引">
                  <a-switch v-decorator="['AAuto', { valuePropName: 'checked' }]"></a-switch>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="存放位置">
                  <a-select
                    v-decorator="['DsID_l']"
                    allowClear
                    placeholder="未选择楼"
                    :options="options_l"
                    @change="getOptions($event, 'options_c')"
                  >
                  </a-select>
                  <div class="text-warning">存放说明：*楼</div>
                </a-form-item>
              </a-col>
              <a-col :span="8" v-show="!$isEmpty(options_c)">
                <a-form-item label="存放位置">
                  <a-select
                    allowClear
                    v-decorator="['DsID_c']"
                    placeholder="未选择楼层"
                    :options="options_c"
                    @change="getOptions($event, 'options_s')"
                  >
                  </a-select>
                  <div class="text-warning">存放说明：*楼层</div>
                </a-form-item>
              </a-col>
              <a-col :span="8" v-show="!$isEmpty(options_s)">
                <a-form-item label="存放位置">
                  <a-select
                    allowClear
                    v-decorator="['DsID_s']"
                    placeholder="未选择室"
                    :options="options_s"
                    @change="getOptions($event, 'options_g')"
                  >
                  </a-select>
                  <div class="text-warning">存放说明：*室</div>
                </a-form-item>
              </a-col>
              <a-col :span="8" v-show="!$isEmpty(options_g)">
                <a-form-item label="存放位置">
                  <a-select
                    allowClear
                    v-decorator="['DsID_g']"
                    placeholder="未选择柜"
                    :options="options_g"
                    @change="getOptions($event, 'options_gc')"
                  >
                  </a-select>
                  <div class="text-warning">存放说明：*柜</div>
                </a-form-item>
              </a-col>
              <a-col :span="8" v-show="!$isEmpty(options_gc)">
                <a-form-item label="存放位置">
                  <a-select
                    allowClear
                    v-decorator="['DsID_gc']"
                    placeholder="未选择柜层"
                    :options="options_gc"
                    @change="getOptions($event, 'options_h')"
                  >
                  </a-select>
                  <div class="text-warning">存放说明：*柜层</div>
                </a-form-item>
              </a-col>
              <a-col v-show="!$isEmpty(options_h)" :span="8">
                <a-form-item label="存放位置">
                  <a-select allowClear v-decorator="['DsID_h']" placeholder="未选择盒" :options="options_h"> </a-select>
                  <div class="text-warning">存放说明：*盒</div>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="16">
                <a-form-item label="描述" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
                  <a-textarea
                    placeholder="请输入描述"
                    v-decorator="['Descr']"
                    :auto-size="{ minRows: 3, maxRows: 5 }"
                  ></a-textarea>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="是否待整改" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
                  <a-switch v-decorator="['AAlter', { valuePropName: 'checked' }]"></a-switch>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-tab-pane>
        <a-tab-pane v-if="!$isEmpty(data)" key="2" tab="档案清单">
          <a-table
            :columns="columnsDir"
            :data-source="ArchivesDir"
            :rowKey="(record, index) => index"
            size="middle"
            :pagination="false"
          >
          </a-table>
        </a-tab-pane>
        <a-tab-pane v-if="!$isEmpty(data) || form.getFieldValue('AAuto')" key="3" tab="检索条件">
          <y-button type="primary" icon="plus" class="m-b-16" @click="handleIndexAction({})">添加条件</y-button>
          <a-table
            :columns="indexColumns"
            :data-source="indexData"
            :rowKey="(record, index) => index"
            size="small"
            :pagination="false"
          >
            <div slot="action" slot-scope="text, record, index">
              <y-button type="link" @click="handleIndexAction(record)">修改</y-button>
              <a-popconfirm
                title="是否删除此检索条件"
                ok-text="删除"
                cancel-text="取消"
                @confirm="handleDelIndex(index)"
              >
                <y-button class="text-error" type="link">删除</y-button>
              </a-popconfirm>
            </div>
          </a-table>
          <a-modal
            :visible="visibleIndex"
            @cancel="handleIndexClose"
            :title="`${$isEmpty(indexItem) ? '添加' : '修改'}检索条件`"
            :okText="$isEmpty(indexItem) ? '添加' : '修改'"
            @ok="handleIndexSubmit"
          >
            <a-form :form="indexForm">
              <a-form-item label="档案名称">
                <a-input
                  placeholder="请输入档案名称"
                  v-decorator="['KeyName', { rules: [{ required: true, message: '请输入档案名称' }] }]"
                ></a-input>
              </a-form-item>
              <a-form-item label="关键字">
                <a-input
                  placeholder="请输入关键字"
                  v-decorator="['KeyValue', { rules: [{ required: true, message: '请输入关键字' }] }]"
                ></a-input>
              </a-form-item>
              <a-form-item label="档案描述">
                <a-textarea
                  placeholder="请输入档案描述"
                  v-decorator="['KeyDesc']"
                  :auto-size="{ minRows: 3, maxRows: 5 }"
                ></a-textarea>
              </a-form-item>
            </a-form>
          </a-modal>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </a-modal>
</template>

<script>
import { getArDropList, getArchivesbyID, postArchives } from '@/api/fileManagement'
import pick from 'lodash.pick'
import moment from 'moment'
import { validIDCard } from '@/utils/validate'
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    visible (n) {
      if (n) {
        this.fetchData()
      }
    }
  },
  data () {
    return {
      validateIDCard (rule, value, callback) {
        if (!value) {
          callback(new Error('请输入身份证'))
        }
        if (!validIDCard(value)) {
          callback(new Error('身份证号输入有误，请重新输入!'))
        }
        callback()
      },
      detailData: {},
      activeKey: '1',
      spinning: false,
      isSubmiting: false,
      form: this.$form.createForm(this, { name: 'fileManagement' }),
      lockTime: false,
      autoIndex: false,
      options_l: [],
      options_c: [],
      options_s: [],
      options_g: [],
      options_gc: [],
      options_h: [],
      // 档案清单
      ArchivesDir: [],
      columnsDir: [
        {
          dataIndex: 'DirName',
          align: 'center',
          title: '材料名称'
        },
        {
          dataIndex: 'CreateDate',
          align: 'center',
          title: '材料形成日期',
          customRender: text => moment(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
          dataIndex: 'Part',
          align: 'center',
          title: '份数'
        },
        {
          dataIndex: 'Pages',
          align: 'center',
          title: '页数'
        },
        {
          dataIndex: 'Descr',
          align: 'center',
          title: '描述'
        }
      ],
      // 检索条件
      visibleIndex: false,
      indexItem: {},
      indexColumns: [
        {
          dataIndex: 'KeyName',
          align: 'center',
          title: '档案名称'
        },
        {
          dataIndex: 'KeyValue',
          align: 'center',
          title: '关键字'
        },
        {
          dataIndex: 'KeyDesc',
          align: 'center',
          title: '档案描述'
        },
        {
          title: '操作',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      indexData: [],
      indexForm: this.$form.createForm(this, { name: 'indexForm' })
    }
  },
  methods: {
    fetchData () {
      const promiseArr = [getArDropList({ lid: 0 })]
      if (!this.$isEmpty(this.data)) {
        promiseArr.push(getArchivesbyID({ archivesid: this.data.ID }))
      }
      this.spinning = true
      Promise.all(promiseArr)
        .then((res) => {
          this.options_l = res[0].map((e) => ({
            value: e.ID,
            label: e.NAME
          }))
          if (!this.$isEmpty(this.data)) {
            const formatNumber = ['DsID_l', 'DsID_c', 'DsID_s', 'DsID_g', 'DsID_gc', 'DsID_h']
            const optionsMap = new Map([
              ['DsID_l', 'options_c'],
              ['DsID_c', 'options_s'],
              ['DsID_s', 'options_g'],
              ['DsID_g', 'options_gc'],
              ['DsID_gc', 'options_h']
            ])
            formatNumber.forEach((key, index) => {
              const value = res[1][key]
              // const nextKey = formatNumber[index + 1]
              if (value) {
                res[1][key] = Number(value)
                if (key !== 'DsID_h') {
                  this.getOptions(Number(value), optionsMap.get(key), false)
                }
                // // 下一级是否有选择 没有不进行加载
                // if (!this.$$isEmpty(res[1][nextKey])) {
                // }
              } else {
                res[1][key] = undefined
              }
            })
            this.detailData = res[1]
            this.$nextTick(() => {
              this.form.setFieldsValue(
                Object.assign(
                  {},
                  pick(res[1], [
                    'Name',
                    'AKey',
                    'AValue',
                    'DsID_l',
                    'DsID_c',
                    'DsID_s',
                    'DsID_g',
                    'DsID_gc',
                    'DsID_h',
                    'Descr'
                  ]),
                  {
                    AAlter: !!Number(this.detailData.AAlter),
                    AAuto: !!Number(this.detailData.AAuto),
                    CreateDate: moment(this.detailData.CreateDate)
                  }
                )
              )
            })
            this.ArchivesDir = this.detailData.ArchivesDir
            this.indexData = this.detailData.ArchivesDetail
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    getOptions (lid, optionsKey, clearFileds = true) {
      // 清空数据 暂时使用switch
      if (clearFileds) {
        switch (optionsKey) {
          case 'options_l':
            this.$nextTick(() => {
              this.form.setFieldsValue({
                DsID_l: undefined,
                DsID_c: undefined,
                DsID_s: undefined,
                DsID_g: undefined,
                DsID_gc: undefined,
                DsID_h: undefined
              })
            })
            this.options_l = []
            this.options_c = []
            this.options_s = []
            this.options_g = []
            this.options_gc = []
            this.options_h = []
            break
          case 'options_c':
            this.$nextTick(() => {
              this.form.setFieldsValue({
                DsID_c: undefined,
                DsID_s: undefined,
                DsID_g: undefined,
                DsID_gc: undefined,
                DsID_h: undefined
              })
            })
            this.options_c = []
            this.options_s = []
            this.options_g = []
            this.options_gc = []
            this.options_h = []
            break
          case 'options_s':
            this.$nextTick(() => {
              this.form.setFieldsValue({
                DsID_s: undefined,
                DsID_g: undefined,
                DsID_gc: undefined,
                DsID_h: undefined
              })
            })
            this.options_s = []
            this.options_g = []
            this.options_gc = []
            this.options_h = []
            break
          case 'options_g':
            this.$nextTick(() => {
              this.form.setFieldsValue({
                DsID_g: undefined,
                DsID_gc: undefined,
                DsID_h: undefined
              })
            })
            this.options_g = []
            this.options_gc = []
            this.options_h = []
            break
          case 'options_gc':
            this.$nextTick(() => {
              this.form.setFieldsValue({
                DsID_gc: undefined,
                DsID_h: undefined
              })
            })
            this.options_gc = []
            this.options_h = []
            break
          default:
          case 'options_h':
            this.$nextTick(() => {
              this.form.setFieldsValue({
                DsID_h: undefined
              })
            })
            this.options_h = []
            break
        }
      }
      if (this.$isEmpty(lid) && lid !== '') return
      this.spinning = true
      getArDropList({ lid: lid })
        .then((res) => {
          this[optionsKey] = res.map((e) => ({
            value: e.ID,
            label: e.NAME
          }))
        })
        .finally(() => {
          this.spinning = false
        })
    },
    // 检索条件添加/修改
    handleIndexSubmit () {
      this.indexForm.validateFields((err, values) => {
        if (!err) {
          if (this.$isEmpty(this.indexItem)) {
            this.indexData.push({
              ...values,
              ID: '',
              LID: this.detailData.ID || '',
              IDNO: this.detailData.IDNO || ''
            })
          } else {
            const index = this.indexData.findIndex((e) => e.ID === this.indexItem.ID)
            if (index !== -1) {
              this.$set(this.indexData, index, {
                ...values,
                ID: this.indexItem.ID,
                LID: this.indexItem.LID,
                IDNO: this.indexItem.IDNO
              })
            }
          }
          this.handleIndexClose()
        }
      })
    },
    handleIndexAction (record = {}) {
      this.indexItem = record
      if (!this.$isEmpty(record)) {
        const { KeyName, KeyValue, KeyDesc } = record
        this.indexForm.setFieldsValue({ KeyName, KeyValue, KeyDesc })
      }
      this.visibleIndex = true
    },
    handleIndexClose () {
      this.indexForm.resetFields()
      this.indexItem = {}
      this.visibleIndex = false
    },
    handleDelIndex (index) {
      this.indexData.splice(index, 1)
    },
    close () {
      this.$emit('update:visible', false)
      this.$emit('update:data', {})
      this.form.resetFields()
      Object.assign(this.$data, this.$options.data.call(this))
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          const { AAlter, AAuto } = values
          values.AAlter = AAlter ? 1 : 0
          values.AAuto = AAuto ? 1 : 0
          const data = Object.assign({}, values, {
            ID: this.detailData.ID || '',
            IDNO: this.detailData.IDNO || '',
            LID: this.detailData.LID || 2,
            ApplyNO: this.detailData.ApplyNO || '',
            DsID_l: values.DsID_l || '',
            DsID_c: values.DsID_c || '',
            DsID_s: values.DsID_s || '',
            DsID_g: values.DsID_g || '',
            DsID_gc: values.DsID_gc || '',
            DsID_h: values.DsID_h || '',
            CreateDate: this.detailData.CreateDate || moment().format('YYYY-MM-DD HH:mm:ss'),
            CreateUserID: this.detailData.CreateUserID || this.$store.getters.userid,
            LastAlterDate: moment().format('YYYY-MM-DD HH:mm:ss'),
            LastAlterUserID: this.$store.getters.userid,
            ArcAddress: '',
            CorG: this.detailData.CorG || '',
            CorGWay: this.detailData.CorGWay || '',
            OutUnit: this.detailData.OutUnit || '',
            PostUnit: this.detailData.PostUnit || '',
            WithUnit: this.detailData.WithUnit || '',
            Reply: this.detailData.Reply || '',
            ForwardUnit: this.detailData.ForwardUnit || '',
            TurnUnit: this.detailData.TurnUnit || '',
            Title: this.detailData.Title || '',
            DocumentNO: this.detailData.DocumentNO || '',
            DocDate: this.detailData.DocDate || '',
            DocCategory: this.detailData.DocCategory || '',
            DocAbstract: this.detailData.DocAbstract || '',
            KeyWord: this.detailData.KeyWord || '',
            ArchivesDir: this.detailData.ArchivesDir || [],
            ArchivesDetail: this.indexData,
            ArchivesDelete: this.detailData.ArchivesDelete || '',
            UserID: this.$store.getters.userid
          })
          if (this.$isEmpty(this.data)) {
            const fileListStr = [
              '贵阳市城镇(非城镇)居民公共租赁住房申请表(表一)',
              '贵阳市城镇(非城镇)居民公共租赁住房审核表(表二)',
              '贵阳市公租房城市低收入家庭认定申请审批表',
              '低保证复印件',
              '申请报告',
              '身份证复印件',
              '户口复印件',
              '结婚证明',
              '现住房情况证明',
              '残疾证复印件',
              '其他材料'
            ]
            data.ArchivesDir = fileListStr.map((e) => ({
              CreateDate: moment().format('YYYY-MM-DD HH:mm:ss'),
              Descr: '',
              DirName: e,
              ID: '',
              LID: '',
              IDNO: '',
              Orders: '',
              Pages: '',
              Part: ''
            }))
            if (AAuto) {
              data.ArchivesDetail.unshift({
                KeyName: values.AKey,
                KeyValue: values.AValue,
                KeyDesc: '自动索引',
                ID: '',
                LID: '',
                IDNO: ''
              })
            }
          }
          this.isSubmiting = true
          postArchives({
            State: this.$isEmpty(this.data) ? 'add' : 'update',
            ArchivesModules: data
          }).then((res) => {
            this.$emit('success', this.$isEmpty(this.data))
            this.$message.success(this.$isEmpty(this.data) ? '档案添加成功' : '档案修改成功')
            this.close()
          })
        }
      })
    },
    hanldeAfterClose () {}
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-calendar-picker {
  width: 100%;
}
</style>
